<template>
  <ry-modal
    :title="isEdit ? '编辑冻存记录' : '新增冻存记录'"
    v-model="visible"
    destroyOnClose
    :confirmLoading="confirmLoading"
    :ryfooter="null"
    width="1000px"
  >
    <div class="table-container cell-storage-modal-body">
      <a-form-model
        ref="formRef"
        :model="formData"
        :rules="activeRules"
        :label-col="modelConfig.labelCol"
        :wrapper-col="modelConfig.wrapperCol"
        class="cell-storage-form"
      >
        <a-row :gutter="24">
          <!-- ==================== 绑定细胞 ==================== -->
          <a-col :span="24" class="section-title">
            <span class="section-marker">&nbsp;</span>绑定细胞
          </a-col>

          <!-- 细胞编号（选择 + 隐藏输入） -->
          <a-col :span="12">
            <a-form-model-item label="细胞编号" prop="cellCode">
              <a-input v-model="formData.cellCode" style="display:none;" />
              <div class="bind-project-tags">
                <template v-if="formData.cellCode">
                  <a-tag color="blue">{{ formData.cellCode }}</a-tag>
                </template>
                <template v-else>
                  <span class="bind-project-placeholder">未选择</span>
                </template>
                <a-button
                  v-if="!isEdit"
                  size="small"
                  style="margin-left:8px;"
                  @click="openCellModal"
                >选择</a-button>
              </div>
            </a-form-model-item>
          </a-col>

          <!-- 项目名称 Tag -->
          <a-col :span="12">
            <a-form-model-item label="项目名称">
              <div class="bind-project-tags">
                <template v-if="applyProjectTagList.length">
                  <a-tag
                    v-for="tag in applyProjectTagList"
                    :key="tag"
                    color="blue"
                  >
                    {{ tag }}
                  </a-tag>
                </template>
                <template v-else>
                  <span class="bind-project-placeholder">--</span>
                </template>
              </div>
            </a-form-model-item>
          </a-col>

          <!-- 客户名称（只读） -->
          <a-col :span="12">
            <a-form-model-item label="客户名称">
              <a-input v-model="formData.nickname" disabled placeholder="未选择" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="联系方式">
              <a-input v-model="formData.phone" disabled placeholder="未选择" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="细胞管数(原)">
              <a-input
                v-model="formData.originalCellNum"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="细胞管数(余)">
              <a-input
                v-model="formData.cellNum"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="细胞数量">
              <a-input
                v-model="formData.quantity"
                disabled
                placeholder="未选择"
              />
            </a-form-model-item>
          </a-col>

          <!-- ==================== 冻存信息 ==================== -->
          <a-col :span="24" class="section-title">
            <span class="section-marker">&nbsp;</span>冻存信息
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="细胞库编号" prop="cellBank">
              <a-input v-model="formData.cellBank" placeholder="请输入细胞库编号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="液氮罐编号" prop="liquidNitrogenTank">
              <a-input v-model="formData.liquidNitrogenTank" placeholder="请输入液氮罐编号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="区" prop="area">
              <a-input v-model="formData.area" placeholder="请输入区" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="架号" prop="rack">
              <a-input v-model="formData.rack" placeholder="请输入架号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="层号" prop="level">
              <a-input v-model="formData.level" placeholder="请输入层号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="盒号" prop="box">
              <a-input v-model="formData.box" placeholder="请输入盒号" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="存储规格" prop="cellSpec">
              <a-input v-model="formData.cellSpec" placeholder="请输入存储规格" />
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="最近检查时间" prop="lastInspection">
              <a-date-picker
                v-model="formData.lastInspection"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                style="width:100%"
              />
            </a-form-model-item>
          </a-col>

<!--          <a-col :span="12">-->
<!--            <a-form-model-item label="状态" prop="status">-->
<!--              <a-select-->
<!--                v-model="formData.status"-->
<!--                allowClear-->
<!--                placeholder="请选择状态"-->
<!--              >-->
<!--                <a-select-option-->
<!--                  v-for="s in statusOptions"-->
<!--                  :key="s.value"-->
<!--                  :value="s.value"-->
<!--                >-->
<!--                  {{ s.label }}-->
<!--                </a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->

          <a-col :span="12">
            <a-form-model-item label="管理人员" prop="manager">
              <a-input v-model="formData.manager" placeholder="请输入管理人员" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 按钮 -->
        <a-form-model-item :wrapper-col="{ span: 24 }" class="form-btn-row">
          <div class="form-btn-group">
            <a-button type="primary" :loading="confirmLoading" @click="handleOk">提交</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>

    <!-- 细胞选择弹框 -->
    <CellSelectModal ref="cellSelectModal" @cell="onCellSelected" />
  </ry-modal>
</template>

<script>
import CellSelectModal from '@/views/freezeRecord/modules/CellSelectModal.vue'
import { cellStorage } from '@/apilist/permission'

export default {
  name: 'CellStorageModal',
  components: { CellSelectModal },
  data() {
    return {
      visible: false,
      isEdit: false,
      confirmLoading: false,
      formData: this.getEmptyForm(),
      statusOptions: [],
      rules: {
        cellCode:            [{ required: true, message: '请选择细胞', trigger: 'change' }],
        cellBank:            [{ required: true, message: '请输入细胞库编号', trigger: 'blur' }],
        liquidNitrogenTank:  [{ required: true, message: '请输入液氮罐编号', trigger: 'blur' }],
        sampleCode:          [{ required: true, message: '请输入样品编号', trigger: 'blur' }],
        status:              [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      modelConfig: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      }
    }
  },

  computed: {
    activeRules() {
      return this.rules
    },
    applyProjectTagList() {
      const codes = this.formData.applyProject || ''
      if (!codes) return []
      return codes
        .split(',')
        .map(c => c.trim())
        .filter(Boolean)
        .map(c => this.$getDictName('APPLY_PROJECT', c))
    }
  },

  created() {
    this.loadStatusDict()
  },

  methods: {
    getEmptyForm() {
      return {
        id: null,
        cellCode: '',
        nickname: '',
        phone: '',
        applyProject: '',
        cellBank: '',
        cellNum: '',
        originalCellNum: '',
        quantity: '',
        liquidNitrogenTank: '',
        area: '',
        rack: '',
        level: '',
        box: '',
        cellSpec: '',
        sampleCode: '',
        lastInspection: null,
        status: '',
        manager: '',
        remark: ''
      }
    },

    loadStatusDict() {
      const arr = this.$getDict('storage_status') || []
      this.statusOptions = arr.map(d => ({
        value: d.dictValue !== undefined ? d.dictValue : d.value,
        label: d.dictLabel !== undefined ? d.dictLabel : d.label
      }))
    },

    /* 修复新增/编辑标题问题 */
    open(record) {
      this.isEdit = !!(record && record.id)
      this.visible = true

      if (this.isEdit) {
        // 编辑模式
        this.confirmLoading = true
        this.formData = this.getEmptyForm()

        window.$axios
          .get(`${cellStorage.byId}/${record.id}`)
          .then(res => {
            const d = res && res.data && (res.data.data || res.data) ? (res.data.data || res.data) : {}
            this.formData = {
              ...this.getEmptyForm(),
              id: d.id || record.id,
              cellCode: d.cellCode || record.cellCode || '',
              nickname: d.nickname || record.nickname || '',
              cellNum: d.cellNum || record.cellNum || '',
              originalCellNum: d.originalCellNum || record.originalCellNum || '',
              quantity: d.quantity || record.quantity || '',
              phone: d.phone || record.phone || '',
              applyProject: d.applyProject || record.applyProject || '',
              cellBank: d.cellBank || '',
              liquidNitrogenTank: d.liquidNitrogenTank || '',
              area: d.area || '',
              rack: d.rack || '',
              level: d.level || '',
              box: d.box || '',
              cellSpec: d.cellSpec || '',
              sampleCode: d.sampleCode || '',
              lastInspection: d.lastInspection || null,
              status: d.status || '',
              manager: d.manager || '',
              remark: d.remark || ''
            }
          })
          .catch(() => {
            this.$message.error('加载详情失败')
            this.formData = { ...this.getEmptyForm(), ...record }
          })
          .finally(() => {
            this.confirmLoading = false
          })
      } else {
        // 新增模式
        this.resetForm()
        this.$nextTick(() => {
          // this.$refs.cellSelectModal && this.$refs.cellSelectModal.open({ stored: 0 })
        })
      }
    },

    openCellModal() {
      if (this.isEdit) return
      this.$refs.cellSelectModal && this.$refs.cellSelectModal.open('notZbfs')
    },

    onCellSelected(cell) {
      if (!cell) return
      this.formData.cellId = cell.id
      this.formData.cellCode = cell.cellCode || ''
      this.formData.cellNum = cell.cellNum || ''
      this.formData.originalCellNum = cell.originalCellNum || ''
      this.formData.quantity = cell.quantity || ''
      this.formData.nickname = cell.nickname || cell.customerName || (cell.businessAccount ? cell.businessAccount.nickname : '') || ''
      this.formData.phone = cell.phone || cell.customerName || (cell.businessAccount ? cell.businessAccount.phone : '') || ''
      this.formData.applyProject = cell.applyProject || ''
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.validateField('cellCode')
      })
    },

    handleOk() {
      if (this.confirmLoading) return
      if (!this.formData.cellCode) {
        this.$message.error('请选择细胞')
        return
      }

      this.$refs.formRef.validate(valid => {
        if (!valid) {
          this.$message.warning('请检查表单填写')
          return
        }

        const api = this.isEdit ? cellStorage.update : cellStorage.insert
        const payload = this.buildSubmitData()

        this.confirmLoading = true
        window.$axios.post(api, payload)
          .then(() => {
            this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
            this.visible = false
            this.$emit('ModalOk')
          })
          .catch(() => {
            this.$message.error(this.isEdit ? '编辑失败' : '新增失败')
          })
          .finally(() => {
            this.confirmLoading = false
          })
      })
    },

    buildSubmitData() {
      return {
        id: this.formData.id,
        cellId: this.formData.cellId,
        cellCode: this.formData.cellCode,
        cellBank: this.formData.cellBank,
        cellNum: this.formData.cellNum,
        originalCellNum: this.formData.originalCellNum,
        quantity: this.formData.quantity,
        liquidNitrogenTank: this.formData.liquidNitrogenTank,
        area: this.formData.area,
        rack: this.formData.rack,
        level: this.formData.level,
        box: this.formData.box,
        cellSpec: this.formData.cellSpec,
        sampleCode: this.formData.sampleCode,
        lastInspection: this.normalizeTime(this.formData.lastInspection),
        status: this.formData.status,
        manager: this.formData.manager,
        remark: this.formData.remark,
        nickname: this.formData.nickname,
        phone: this.formData.phone,
        applyProject: this.formData.applyProject
      }
    },

    normalizeTime(val) {
      if (!val) return null
      if (val && typeof val === 'object' && typeof val.format === 'function') {
        return val.format('YYYY-MM-DD HH:mm:ss')
      }
      if (val instanceof Date) {
        const d = val
        const pad = n => (n < 10 ? '0' + n : n)
        return (
          d.getFullYear() + '-' +
          pad(d.getMonth() + 1) + '-' +
          pad(d.getDate()) + ' ' +
          pad(d.getHours()) + ':' +
          pad(d.getMinutes()) + ':' +
          pad(d.getSeconds())
        )
      }
      if (typeof val === 'string') return val
      return null
    },

    handleCancel() {
      this.visible = false
    },

    resetForm() {
      this.formData = this.getEmptyForm()
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    }
  }
}
</script>

<style scoped>
.cell-storage-modal-body { padding: 0 8px; }
.cell-storage-form .ant-form-item { margin-bottom: 16px; }
.section-title {
  font-weight: 600;
  margin-bottom: 10px;
  margin-left: 20px;
}
.section-marker {
  background-color: #3acaca;
  margin-right: 4px;
}
.form-btn-row { margin-top: 8px; }
.form-btn-group { display: flex; justify-content: center; gap: 24px; }
.bind-project-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  min-height: 32px;
  gap: 4px;
}
.bind-project-placeholder {
  color: #999;
}
</style>
